import axios from "axios";
import {KEY_USER_ID, UserInfo} from "@/store/modules/useUserStore";
import router from "@/routes";
import {CODE_NO_AUTHORIZATION, CODE_OK} from "@/api/consts";
 const requests = axios.create({
     //baseURL: import.meta.env.VITE_API_URL,
     timeout:20000,
 });
 requests.interceptors.request.use((config)=>{
    config = config || {};
    try {
        //这里不能使用pinia，因为可能vue还没有加载到pinia
        const user = JSON.parse(localStorage.getItem(KEY_USER_ID) || '{}') as UserInfo;
        if(user.token){
            config.headers!['Authorization'] = `Bearer ${user.token}`;
        }
    }catch (e){}
     return config;
 });
 requests.interceptors.response.use((resp)=>{
    const {code,msg} = resp.data || {} ;
    if(code!==CODE_OK){
        return Promise.reject(msg)
    }
    if(code === CODE_NO_AUTHORIZATION){
        router.push({name:'Login'}).then();
        return Promise.reject(msg);
    }
    return Promise.resolve(resp);
 },(error)=>{
     return Promise.reject(error);
 });
 export default requests;